/////////////////////////////////////////////////////////////////////////////
// Purpose:     String formating similar to sprintf
// Author:      Jesus Gonzalez
// Modified by:
// Copyright:   (c) 2003-2013 Jesus Gonzalez <jgonzalez@gdr-sistemas.com>
// License:     BSD License
/////////////////////////////////////////////////////////////////////////////

#include "SmartLib/FormatString.h"
#include "SmartLib/ByteArray.h"

#include <stdio.h>
#include <stdarg.h>

#include "Log.h"

#define _INITIAL_LENGTH	1024

std::string vFormatString( const char *fmt, va_list ap )
{
    if ( !fmt ) return "";

    char *buffer = new char[_INITIAL_LENGTH];

    int n = vsnprintf( buffer, _INITIAL_LENGTH, fmt, ap );

    if( n >= _INITIAL_LENGTH )
    {
    	// Didn't get enough space
    	delete [] buffer;
    	buffer = new char [n + 1];

    	n = vsnprintf( buffer, n + 1, fmt, ap );
    }

    if( n < 0 ) return "";

    std::string ret( buffer );
    delete [] buffer;
    return ret;
}

std::string FormatString( const char *fmt, ... )
{
    va_list args;
    va_start( args, fmt );
    std::string ret = vFormatString( fmt, args );
    va_end( args );
    return ret;
}

std::string FormatHexString( const ByteArray& data,
                             std::string indent,
                             std::string separator,
                             unsigned int bytes_per_line )
{
	std::string out;
	unsigned int i;

	for( i = 0; i < data.size(); i++ )
	{
		if( !(i % bytes_per_line) )
		{
			if(i > 0)
			{
				out += "\n";
			}
			out += indent;
		}
		out += FormatString( "%02X", (unsigned char)data[i] );
		out += separator;
	}

	return out;
}

std::string FormatHexString( const ByteArray& data,
                             unsigned int indent,
                             unsigned int separator,
                             unsigned int bytes_per_line )
{
	std::string sep_str( separator, ' '  );
	std::string idt_str( indent, ' ' );

	return FormatHexString( data, idt_str, sep_str, bytes_per_line );
}
